<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/12/15
 * Time: 10:06
 */

class DbTools
{
    private static $conn;
    private static $host='127.0.0.1';
    private static $user='root';
    private static $password='root';
    private static $database='bank';
    private static $port="3306";
    private static $socket=null;

    public static function initDb($host='', $user='', $password='', $database='', $port='', $socket=''){
        if (!empty($host)){
            self::$host = $host;
        }
        if (!empty($user)){
            self::$user = $user;
        }
        if (!empty($password)){
            self::$password = $password;
        }
        if (!empty($database)){
            self::$database = $database;
        }
        if (!empty($port)){
            self::$port = $port;
        }
        if (!empty($socket)){
            self::$socket = $socket;
        }
        self::$conn = new mysqli();
        self::$conn->connect(self::$host,self::$user,self::$password,self::$database,self::$port,self::$socket);
        if (!empty(self::$conn->connect_error)){
            echo '数据库连接错误：'.self::$conn->connect_error;
        }else{
//            echo '数据库连接成功！<br/>';
        }
    }
    public static function select($sql){
        $result = self::$conn->query($sql);
        $data = [];
        while (true){
            $row = $result->fetch_assoc();
            if (empty($row)){
                break;
            }
            $data[] = $row;
        }
        $result->close();
        return $data;
    }
    public static function noSelect($sql){
        $result = self::$conn->query($sql);
        if ($result){
            if (self::$conn->affected_rows>0){
                return [
                    'status'=>true,
                    'message'=>self::$conn->affected_rows
                ];
            }else{
                return [
                    'status'=>false,
                    'message'=>'影响记录数为0'
                ];
            }
        }else{
            return [
                'status'=>false,
                'message'=>self::$conn->error
            ];
        }
    }
    public static function close(){
        self::$conn->close();
    }
}